package cn.imvc.app.models;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.IndexData;
import cn.imvc.app.entities.InventoryFlow;
import cn.imvc.app.entities.User;
import cn.imvc.app.repositories.InventoryFlowRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;
import cn.imvc.data.util.JpqlUtil;

@Service
public class InventoryFlowModelImpl implements InventoryFlowModel {

	@Autowired
	InventoryFlowRepository inventoryFlowRepository;
	@Autowired
	UserModel userModel;
	
	public Page<InventoryFlow> find(ViewRequest viewRequest) {
		return inventoryFlowRepository.findAll("i","InventoryFlow i",ModelUtil.OrderByIdDesc(viewRequest));
	}

	public InventoryFlow get(int id) {
		return inventoryFlowRepository.findOne(id);
	}

	public InventoryFlow save(InventoryFlow inventoryFlow) {
		User user = userModel.getSessionUser();
		inventoryFlow.setUserId(user.getId());
		inventoryFlow.setCreatedAt(new Date());
		return inventoryFlowRepository.saveAndFlush(inventoryFlow);
	}

	public InventoryFlow update(InventoryFlow inventoryFlow) {
		return inventoryFlowRepository.saveAndFlush(inventoryFlow);
	}

	public void delete(int id) {
		inventoryFlowRepository.delete(id);
	}

	public void deleteBatch(int[] ids) {
		for (int id : ids) {
			delete(id);
		}
	}

	public Page<Object[]> findObjectPage(ViewRequest viewRequest) {
		if(viewRequest == null){
			viewRequest=new ViewRequest();
		}
		String sql = "select g.name,s.specName,i.count,i.afterChange,i.remark,u.name as username,i.createdAt from inventory_flow i left join"
				+ " user u on i.userId = u.id left join goods g on i.goodsId = g.id left join goods_sku s on i.goodsSkuId = s.id"
				+JpqlUtil.toWhere(viewRequest.getParams())+" order by i.createdAt desc";
		viewRequest = ModelUtil.OrderByIdDesc(viewRequest);
		PageRequest pageRequest = new PageRequest(viewRequest.getPage(), viewRequest.getSize());
		return inventoryFlowRepository.findAllSql(sql, pageRequest);
	}
}
